package com.daffodil.workable.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.daffodil.core.util.HqlUtils;
import com.daffodil.core.dao.JpaDao;
import com.daffodil.core.entity.Query;
import com.daffodil.workable.entity.WorkableNode;
import com.daffodil.workable.service.IWorkableNodeService;
import com.daffodil.util.StringUtils;

/**
 * -节点信息Service接口业务实现层
 * @author yweijian
 * @date 2022-04-07
 * @version 1.0
 * @description
 */
@Service
public class WorkableNodeServiceImpl implements IWorkableNodeService {

    @Autowired
    private JpaDao<String> jpaDao;

    @Override
    public List<WorkableNode> selectWorkableNodeList(Query<WorkableNode> query) {
        StringBuffer hql = new StringBuffer("from WorkableNode where 1=1 ");
        List<Object> paras = new ArrayList<Object>();
        HqlUtils.createHql(hql, paras, query);
        return jpaDao.search(hql.toString(), paras, WorkableNode.class, query.getPage());
    }

    @Override
    public WorkableNode selectWorkableNodeById(String id) {
        return jpaDao.find(WorkableNode.class, id);
    }

    @Override
    @Transactional
    public void insertWorkableNode(WorkableNode workableNode) {
        jpaDao.save(workableNode);
    }

    @Override
    @Transactional
    public void updateWorkableNode(WorkableNode workableNode) {
        jpaDao.update(workableNode);
    }

    @Override
    @Transactional
    public void deleteWorkableNodeByIds(String[] ids) {
        jpaDao.delete(WorkableNode.class, ids);
        for(String id : ids) {
            WorkableNode node = jpaDao.find(WorkableNode.class, id);
            if(StringUtils.isNotNull(node)) {
                List<Object> paras = new ArrayList<Object>();
                paras.add(node.getTaskId());
                paras.add(node.getNodeId());
                jpaDao.delete("delete from WorkableForm where taskId = ? and nodeId = ?", paras);
                jpaDao.delete(node);
            }
        }
    }

    @Override
    public WorkableNode selectWorkableNodeByTaskIdAndNodeId(String taskId, String nodeId) {
        if(StringUtils.isEmpty(taskId) || StringUtils.isEmpty(nodeId)) {
            return null;
        }
        List<Object> paras = new ArrayList<Object>();
        paras.add(taskId);
        paras.add(nodeId);
        return jpaDao.find("from WorkableNode where taskId = ? and nodeId = ?", paras, WorkableNode.class);
    }

    @Override
    public WorkableNode selectStartWorkableNodeByTaskId(String taskId) {
        if(StringUtils.isEmpty(taskId)) {
            return null;
        }
        return jpaDao.find("from WorkableNode where modelId = 'start-node' and type = 'start' and taskId = ?", taskId, WorkableNode.class);
    }

}
